<?php 


if (! function_exists('session')) {

    function session($key)
    {
        if($key && isset($_SESSION[$key])){
            return $_SESSION[$key];
        }
        return "";
    }
}

if (! function_exists('dd')) {

	function dd($args)
	{
        echo "<pre>";

             print_r($args);

		die();
	}
}

if (! function_exists('wlog')) {

    function wlog($msg, $t='app')
    {
        try{
            $r = config('global');
            $root = $r['upload']['dir'];

            $msg = is_string($msg)?$msg:json_encode($msg);
            $f = fopen($root.$t.".txt",'a') or die("Unable to open file!");
            $msg = '['.date('Y-m-d H:i:s').'] '.$msg."\n";
            fwrite($f,$msg);
            fclose($f);
        }catch (\Exception $e){
            //Log::error($type.'.log file write fail');
        }
    }
}

if (! function_exists('hlog')) {

    function hlog($msg, $t='app')
    {
        try{
            $r = config('global');
            $root = $r['upload']['dir'];

            $msg = is_string($msg)?$msg:json_encode($msg);
            $f = fopen($root.$t.".html",'a') or die("Unable to open file!");
            $msg = '['.date('Y-m-d H:i:s').'] '.$msg."\n";
            fwrite($f,$msg);
            fclose($f);
        }catch (\Exception $e){
            //Log::error($type.'.log file write fail');
        }
    }
}





if (! function_exists('input_int')) {

    function input_int($key)
    {
        return intval($_REQUEST[$key]);
    }
}


if (! function_exists('input_str')) {

    function input_str($key)
    {
    	if(isset($_REQUEST[$key])){
    		return addslashes(htmlspecialchars(trim($_REQUEST[$key])));
    	}
    	return '';
    }
}

if (! function_exists('f_str')) {

    function f_str($str)
    {
        return addslashes(htmlspecialchars(trim($str)));
    }
}

if (! function_exists('getCDNUrl2')) {

    function getCDNUrl2($path)
    {
        if (empty($path)) {
            return '';
        }
        if(strpos($path,'http')===false)
            return 'http://newapi.yueashop.com/'.ltrim($path,'/');
        else
            return $path;
    }
}


if (! function_exists('fun_price')) {

    function fun_price($t)
    {
        return $t ? number_format($t, 2, ".", "") : '0.00';
    }
}

if (! function_exists('f_ids')) {

    function f_ids($str)
    {
        if(!$str) return '';
        $ids = explode(',', $str);
        $ids = array_map(function($v){
            return intval($v);
        }, $ids);

        $ids = array_unique($ids);

        return $ids ? implode(',', $ids) : "";
    }
}

if (! function_exists('fps')) {

    function fps($t)
    {
        return fun_price($t);
    }
}

if (! function_exists('sfps')) {

    function sfps($t)
    {
        return fun_price(f_str($t));
    }
}

if (! function_exists('json')) {

    function json($data)
    {
    	header('Content-Type:application/json;charset="utf-8"');
        echo json_encode($data);die();
    }
}

if (! function_exists('redirect')) {

    function redirect($url, $code = null)
    {
        header("Location:$url", true, $code);
        exit;
    }
}

if (! function_exists('price_format')) {

    function price_format($num)
    {
        return $num ? number_format($num, 2, ".", "") : "0.00";
    }
}

if (! function_exists('mobile_format')) {

    function mobile_format($mobile)
    {
        return $mobile ? substr($mobile, 0, 3) .'***' . substr($mobile, -4) : '---';
    }
}

if (! function_exists('_rate')) {

    function _rate($t1 , $t2)
    {
        return $t2 >0 ? round(100*($t1-$t2) / $t2) : "";
    }
}

if (! function_exists('month_diff')) {

    function month_diff($t1 , $t2)
    {
        $y1 = date('Y', strtotime($t1));
        $m1 = date('m', strtotime($t1));

        $y2 = intval(date('Y', strtotime($t2)));
        $m2 = intval(date('m', strtotime($t2)));

        return ($y1 - $y2) * 12 + ($m1 - $m2);
    }
}

if (! function_exists('config')) {

    function config($name)
    {
        $path = APP_PATH.'/config/'.$name.'.php';

        if(file_exists($path)){
            return include $path;
        }
        return [];
    }
}

if (! function_exists('lang')) {

    function lang($code, $msg="", $defaultLang='zh-CN')
    {
        if($msg) return $msg;

        if(file_exists(APP_PATH.'/lang/'.$defaultLang.'.php')){
            $lang = require APP_PATH.'/lang/'.$defaultLang.'.php';
            if($lang && is_array($lang)) {
                $msg = isset($lang[$code]) ? $lang[$code] : 'error';
            }
            return $msg;
        }
        return $code;
    }
}

if (! function_exists('feeHandle')) {

    function feeHandle($fee){
        if (is_numeric($fee)) {
            list($int, $decimal) =  explode('.', $fee);
            $int = preg_replace('/(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))/', ',',$int);
            if ($decimal)$int .= '.'. $decimal;
            return $int;
        }
    }
}

if (! function_exists('fw')) {

    function fw($num){
        if (is_numeric($num) && $num>=10000) {
            return (floor($num/1000)/10) .'w';
        }
        return $num;
    }
}

if (! function_exists('pay')) {

    function pay($name, $config = false)
    {
        require_once(APP_PATH."/vendor/autoload.php");

        if($name == "alipay") {
            if(!$config) {
                $c =config('pay');
                $config = $c['alipay'];
            }
            return Yansongda\Pay\Pay::alipay($config);
        }else if($name=="wxpay") {
            if(!$config) {
                $c =config('pay');
                $config = $c['wxpay'];
            }
            return Yansongda\Pay\Pay::wechat($config);
        }

        return false;
    }
}

if (! function_exists('ajax_return')) {

    function ajax_return($code='200', $msg = '操作成功')
    {
        $data = ['code' => $code, 'msg' =>  $msg];
        echo json_encode($data);
        exit;
    }
}

if (! function_exists('getGoodsTypeByPrice')) {

    function getGoodsTypeByPrice($gd)
    {
        if($gd['profit']>0){
            return 2;
        }else if($gd['shop_group_price']>0 && $gd['shop_point']>0){
            return 3;
        }else if($gd['is_youhuiquan']==1){
            return 4;
        }else{
            return 1;
        }
    }
}

if (! function_exists('imgUrl')) {

    function imgUrl($url)
    {
        if (empty($url))
            return $url;

        if (substr($url,0, 7) == 'http://' || substr($url,0, 8) == 'https://'){
            return $url;
        }
        return 'http://cdn01.smallmitao.com/' . $url;
    }
}

if (! function_exists('isHttpUrl')) {

    function isHttpUrl($url)
    {
        if (substr($url,0, 7) == 'http://' || substr($url,0, 8) == 'https://'){
            return true;
        }
        return false;
    }
}


if (! function_exists('lastQueryParams')) {

    function lastQueryParams()
    {
        $a = parse_url($_SERVER['HTTP_REFERER']);
        return isset($a['query']) && $a['query'] ? $a['query'] : "" ;
    }
}

/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
if (!function_exists('httpPost')) {
    function httpPost($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {

            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        //curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);  //php5.6 curl传文件需要加上这句
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}
if (!function_exists('is_mobile')) {
    function is_mobile()
    {
        $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
        $mobile_browser = '0';
        if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
            $mobile_browser++;
        if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
            $mobile_browser++;
        if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
            $mobile_browser++;
        if (isset($_SERVER['HTTP_PROFILE']))
            $mobile_browser++;
        $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
        $mobile_agents = array(
            'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
            'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
            'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
            'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
            'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
            'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
            'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
            'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
            'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
        );
        if (in_array($mobile_ua, $mobile_agents))
            $mobile_browser++;
        if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
            $mobile_browser++;
        // Pre-final check to reset everything if the user is on Windows
        if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
            $mobile_browser = 0;
        // But WP7 is also Windows, with a slightly different characteristic
        if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
            $mobile_browser++;
        if ($mobile_browser > 0)
            return true;
        else
            return false;
    }
}
if (!function_exists('get_delivery_sn')) {
    function get_delivery_sn()
    {
        mt_srand((double)microtime() * 1000000);
        return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
}
